import type { ResponseData } from '@/utils/types.d';
import { SUCCESS_CODE } from '@/utils/types.d';
import type { CreateMemberCardType, MemberCardTableItem, UpdateMemberCardType } from './types.d';
import request from '@/utils/request';

export async function queryMemberCards(data: any, sort: any) {
  const res: ResponseData<{ total: number; data: MemberCardTableItem[] }> = await request(
    '/api/member/v1.0.0/cards',
    {
      params: {
        data,
        sort,
      },
    },
  );
  if (res?.code === SUCCESS_CODE)
    return { success: true, total: res.data.total, data: res.data.data };
  return { success: false, total: 0, data: [] };
}

export async function createMemberCards(params: CreateMemberCardType) {
  const res = await request('/api/member/v1.0.0/card', {
    method: 'POST',
    data: params,
  });
  if (res?.code === SUCCESS_CODE)
    return {
      data: res.data,
      success: true,
      message: '添加成功',
    };
  return { data: res?.data, success: false, message: res?.message || '添加失败' };
}

export async function getMemeberCard(cardNo: string) {
  const res: ResponseData<MemberCardTableItem> = await request(`/api/member/v1.0.0/card/${cardNo}`);
  if (res?.code === SUCCESS_CODE) return { success: true, data: res.data, message: '成功' };
  return { success: false, data: null, message: res.message || '获取失败' };
}

export async function updateMemberCard(cardNo: string, data4up: UpdateMemberCardType) {
  if (!cardNo || !data4up || Object.keys(data4up).length === 0)
    return { success: false, message: '更新失败，请填入需要更新的信息' };
  const res: ResponseData<null> = await request(`/api/member/v1.0.0/card/${cardNo}`, {
    method: 'PUT',
    data: data4up,
  });
  if (res?.code === SUCCESS_CODE) {
    return { success: true, data: res.data, message: '更新成功' };
  }
  return { success: false, data: res?.data, message: res?.message || '更新失败' };
}

export async function removeMemberCard(cardNo: string) {
  const res: ResponseData<null> = await request(`/api/member/v1.0.0/card/${cardNo}`, {
    method: 'DELETE',
  });
  if (res?.code === SUCCESS_CODE) return { success: true, message: '删除成功' };
  return { success: false, message: res?.message || '删除失败' };
}
